package com.example.redislearning.controller;

import com.example.redislearning.service.LotteryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 积分抽奖控制器
 * 提供抽奖活动管理的REST API
 */
@RestController
@RequestMapping("/api/lottery")
public class LotteryController {

    @Autowired
    private LotteryService lotteryService;

    /**
     * 创建抽奖活动
     */
    @PostMapping("/activities")
    public ResponseEntity<Map<String, Object>> createActivity(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String activityId = (String) request.get("activityId");
            String activityName = (String) request.get("activityName");
            String description = (String) request.get("description");
            int totalPrize = (Integer) request.get("totalPrize");
            int dailyPrize = (Integer) request.get("dailyPrize");
            String startTimeStr = (String) request.get("startTime");
            String endTimeStr = (String) request.get("endTime");
            Map<String, Integer> prizePool = (Map<String, Integer>) request.get("prizePool");
            
            LocalDateTime startTime = LocalDateTime.parse(startTimeStr);
            LocalDateTime endTime = LocalDateTime.parse(endTimeStr);
            
            boolean success = lotteryService.createLotteryActivity(
                activityId, activityName, description, totalPrize, dailyPrize, 
                startTime, endTime, prizePool
            );
            
            response.put("success", success);
            response.put("message", success ? "抽奖活动创建成功" : "抽奖活动创建失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 参与抽奖
     */
    @PostMapping("/participate")
    public ResponseEntity<Map<String, Object>> participateLottery(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Integer userId = Integer.valueOf(request.get("userId").toString());
            String activityId = (String) request.get("activityId");
            
            Map<String, Object> result = lotteryService.participateLottery(userId, activityId);
            
            response.putAll(result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "参与失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取抽奖活动详情
     */
    @GetMapping("/activities/{activityId}")
    public ResponseEntity<Map<String, Object>> getActivity(@PathVariable String activityId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> activity = lotteryService.getLotteryActivity(activityId);
            
            if (activity == null) {
                response.put("success", false);
                response.put("message", "抽奖活动不存在");
                return ResponseEntity.notFound().build();
            }
            
            response.put("success", true);
            response.put("data", activity);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取中奖用户列表
     */
    @GetMapping("/activities/{activityId}/winners")
    public ResponseEntity<Map<String, Object>> getWinners(
            @PathVariable String activityId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Map<String, Object>> winners = lotteryService.getWinners(activityId, page, size);
            
            response.put("success", true);
            response.put("data", winners);
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取活动参与用户数量
     */
    @GetMapping("/activities/{activityId}/participants/count")
    public ResponseEntity<Map<String, Object>> getParticipantCount(@PathVariable String activityId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Integer count = lotteryService.getParticipantCount(activityId);
            
            response.put("success", true);
            response.put("count", count);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取用户参与状态
     */
    @GetMapping("/participation/status")
    public ResponseEntity<Map<String, Object>> getUserParticipationStatus(
            @RequestParam Integer userId,
            @RequestParam String activityId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> status = lotteryService.getUserParticipationStatus(userId, activityId);
            
            response.put("success", true);
            response.put("data", status);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取用户抽奖历史
     */
    @GetMapping("/history/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserLotteryHistory(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Map<String, Object>> history = lotteryService.getUserLotteryHistory(userId, page, size);
            
            response.put("success", true);
            response.put("data", history);
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 结束抽奖活动
     */
    @PostMapping("/activities/{activityId}/end")
    public ResponseEntity<Map<String, Object>> endActivity(@PathVariable String activityId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = lotteryService.endLotteryActivity(activityId);
            
            response.put("success", success);
            response.put("message", success ? "抽奖活动已结束" : "结束失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "结束失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取所有活动列表
     */
    @GetMapping("/activities")
    public ResponseEntity<Map<String, Object>> getAllActivities() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Map<String, Object>> activities = lotteryService.getAllActivities();
            
            response.put("success", true);
            response.put("data", activities);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取用户积分余额
     */
    @GetMapping("/points/{userId}")
    public ResponseEntity<Map<String, Object>> getUserPoints(@PathVariable Integer userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 这里应该从用户服务获取，简化实现
            response.put("success", true);
            response.put("points", 1000); // 模拟用户积分
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取抽奖概率信息
     */
    @GetMapping("/activities/{activityId}/probabilities")
    public ResponseEntity<Map<String, Object>> getProbabilities(@PathVariable String activityId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> activity = lotteryService.getLotteryActivity(activityId);
            
            if (activity == null) {
                response.put("success", false);
                response.put("message", "活动不存在");
                return ResponseEntity.notFound().build();
            }
            
            Map<String, Integer> prizePool = (Map<String, Integer>) activity.get("prizePool");
            Map<String, Object> probabilities = new HashMap<>();
            
            int totalPrize = 0;
            for (Integer count : prizePool.values()) {
                totalPrize += count;
            }
            
            for (Map.Entry<String, Integer> entry : prizePool.entrySet()) {
                double probability = totalPrize > 0 ? (entry.getValue() * 100.0 / totalPrize) : 0;
                probabilities.put(entry.getKey(), String.format("%.2f%%", probability));
            }
            
            response.put("success", true);
            response.put("data", probabilities);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取活动统计信息
     */
    @GetMapping("/activities/{activityId}/statistics")
    public ResponseEntity<Map<String, Object>> getActivityStatistics(@PathVariable String activityId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> activity = lotteryService.getLotteryActivity(activityId);
            
            if (activity == null) {
                response.put("success", false);
                response.put("message", "活动不存在");
                return ResponseEntity.notFound().build();
            }
            
            Integer participantCount = lotteryService.getParticipantCount(activityId);
            List<Map<String, Object>> winners = lotteryService.getWinners(activityId, 1, 10);
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("participantCount", participantCount);
            statistics.put("winnerCount", winners.size());
            statistics.put("activityInfo", activity);
            
            response.put("success", true);
            response.put("data", statistics);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}